package com.wisdudu.blank.support.widget.esptouch.helper;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.orhanobut.logger.Logger;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Admin on 2015/11/12.
 */
public class ServerSocketS {

    private Socket socket;
    private static OutputStream os;
    static InputStream in;
    private boolean issend;
    private static SoketThread soketThread;
    private String mMac;
    private Handler mhandler;

    public static void stopSocketThread() {
        if (soketThread != null && soketThread.ss != null) {
            try {
                soketThread.ss.close();
                if (os != null) {
                    os.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void serviceSingle(Handler handler, String Mac) {
        mhandler = handler;
        mMac = Mac;
        if (EqmentAsyncTask.shouldStop) {
            return;
        }
        soketThread = new SoketThread();
        soketThread.start();
    }

    public class SoketThread extends Thread {
        public volatile ServerSocket ss;

        @Override
        public void run() {
            try {
                Log.i("testq", "unbinded");
                ss = new ServerSocket();
                ss.setReuseAddress(true);
                Log.i("testq", "binding");
                ss.bind(new InetSocketAddress(8000));
                Log.i("testq", "binded");
                ss.setSoTimeout(10000);
                socket = ss.accept();
                in = socket.getInputStream();
                byte[] bb = readStream(in);
                String inStr = "{" + new String(bb) + "}";
                Log.i("testq", "instr:-" + inStr);
                JSONObject object = new JSONObject(inStr);
                // user:18FE34FA25CA,password:666666,type:DC
                String user = object.getString("user");
                String password = object.getString("password");
                String type = object.getString("type");
                Logger.e(user + ",,," + mMac);
                Log.i("testq", "新连接：" + user + "*" + password + "*" + type);
                Log.i("testq", "新连接：mMac:" + mMac);
                os = socket.getOutputStream();
                if (!TextUtils.isEmpty(user) && user.equalsIgnoreCase(mMac)) {
                    if (mhandler != null) {
                        Log.i("testq", "新连接成功");
                        Message msg = new Message();
                        msg.what = 5;
                        msg.obj = object;
                        mhandler.sendMessage(msg);
                        issend = true;
                    }
                    os.write("OK".getBytes("utf-8"));
                } else {
                    if (!user.equalsIgnoreCase(mMac)) {
                        Log.i("testq", "SN不一致");
//                        mhandler.sendEmptyMessage(10);
                    }
                    Log.i("testq", "新连接失败");
                    if (mhandler != null) {
                        mhandler.sendEmptyMessage(10);
                        issend = true;
                    }
                    os.write("Fail".getBytes("utf-8"));
                }
            } catch (Exception e) {
                Log.i("testq", "新连接异常抛出");
                if (mhandler != null) {
                    mhandler.sendEmptyMessage(4);
                }
                e.printStackTrace();
            } finally {
//                if (mhandler != null) {
//                    mhandler.removeCallbacks(stopSocketThread);
//                }
                try {
                    if (os != null) {
                        os.close();
                    }
                    if (in != null) {
                        in.close();
                    }
                    Log.i("testq", "关闭新连接");
                    if (socket != null) {
                        socket.close();
                    }
                    if (ss != null) {
                        ss.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("testq", "关闭流客户端等失败");
                }
            }
        }

    }

    /**
     * @param inStream
     * @return 字节数组
     * @throws Exception
     * @功能 读取流
     */
    public byte[] readStream(InputStream inStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inStream.available();
            if (EqmentAsyncTask.shouldStop) {
                break;
            }
        }
        byte[] b = new byte[count];
        inStream.read(b);
        return b;
    }
}
